import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/bean/receive_data_bean.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

import '../../../ble/protocol_data_util.dart';

class WatchRadioGroupSettingPage extends StatefulWidget {
  const WatchRadioGroupSettingPage({super.key});

  @override
  State<WatchRadioGroupSettingPage> createState() => _WatchRadioGroupSettingPageState();
}

class _WatchRadioGroupSettingPageState extends State<WatchRadioGroupSettingPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址
  String _title = ""; //页面标题
  String _mainTitle = ""; //主标题
  String _subTitle = ""; //子标题
  String _mainTitle2 = ""; //第二行主标题
  String _subTitle2 = ""; //第二行子标题
  String _content1 = ""; //第一行的内容
  String _content2 = ""; //第二行的内容
  int _contentIndex1 = 0; //第一行内容的索引
  int _contentIndex2 = 0; //第一行内容的索引
  String _rb0 = "";
  String _rb1 = "";
  String _rb2 = "";

  bool _groupVisibility = true; //RadioGroup信息是否可见
  bool _secondVisibility = false; //第二行信息是否可见
  bool _rb2Visibility = false; //第二行信息是否可见

  // int _selectedValue = 0; //RadioGroup选择结果

  final _trailingStyle = const TextStyle(color: Color(0xFF3075E9));
  final _titleStyle = const TextStyle(fontSize: 18);
  final _confirmColor = const Color(0xFF3075E9);

  final _controller = Get.put(WatchSettingController());

  final List<String> _brightnessList = []; //屏幕亮度时长列表
  final List<String> _shakeList = []; //震动强度列表
  final List<String> _languageList = [
    "简体中文",
    "繁体中文",
    "英语",
    "西班牙语",
    "俄语",
    "日语",
    "韩语",
    "法语",
    "葡萄牙语"
  ]; //语言列表

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_title > $_mac");
    _controller.getBleData(_mac, _functionId);
    _initStyle(_functionId);

    //屏幕亮度时长列表
    _brightnessList.add("常亮");
    for (int i = 1; i <= 60; i++) {
      _brightnessList.add("$i秒钟");
    }

    for (int i = 0; i <= 10; i++) {
      _shakeList.add("$i次");
    }
  }

  @override
  Widget build(BuildContext context) {
    ever(
      _controller.needClosePage,
      (need) => {
        if (need == 2) {Get.back()}
      },
    );

    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Column(
        children: [
          //第一行标题
          ListTile(
            title: Text(_mainTitle, style: _titleStyle),
            subtitle: Text(_subTitle),
            trailing: Obx(
              () => Text(
                _getTrailingContent(_controller.receiveDataBean.value),
                style: _trailingStyle,
              ),
            ),
            onTap: () async {
              _clickFirstContent();
            },
          ),
          //RadioGroup组
          Visibility(
            visible: _groupVisibility,
            child: Column(
              children: <Widget>[
                Obx(
                  () => RadioListTile<int>(
                    value: 0,
                    title: Text(_rb0),
                    // 紧凑程度
                    visualDensity: const VisualDensity(vertical: -4),
                    groupValue: _controller.radioIndex.value,
                    activeColor: _confirmColor,
                    onChanged: (value) {
                      _controller.updateRadioIndex(value ?? 0);
                    },
                  ),
                ),
                Obx(
                  () => RadioListTile<int>(
                    value: 1,
                    title: Text(_rb1),
                    // 紧凑程度
                    visualDensity: const VisualDensity(vertical: -4),
                    activeColor: _confirmColor,
                    groupValue: _controller.radioIndex.value,
                    onChanged: (value) {
                      _controller.updateRadioIndex(value ?? 0);
                    },
                  ),
                ),
                Visibility(
                  visible: _rb2Visibility,
                  child: Obx(
                    () => RadioListTile<int>(
                      value: 2,
                      title: Text(_rb2),
                      // 紧凑程度
                      visualDensity: const VisualDensity(vertical: -4),
                      activeColor: _confirmColor,
                      groupValue: _controller.radioIndex.value,
                      onChanged: (value) {
                        _controller.updateRadioIndex(value ?? 0);
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),

          //第二行标题
          Visibility(
            visible: _secondVisibility,
            child: ListTile(
              title: Text(_mainTitle2, style: _titleStyle),
              subtitle: Text(_subTitle2),
              trailing: Obx(
                () => Text(
                  _getTrailingContent2(_controller.receiveDataBean.value),
                  style: _trailingStyle,
                ),
              ),
              onTap: () {
                // Log.d("点击了目标内容");
                _clickSecondContent();
              },
            ),
          ),
          //占位
          const Expanded(child: SizedBox()),
          //确认按钮
          Container(
            width: double.infinity,
            height: 46,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            child: TextButton(
              onPressed: () {
                _confirm();
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.blue),
                foregroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(
                  const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                ),
              ),
              child: const Text('确认'),
            ),
          ),
          const SizedBox(height: 60),
        ],
      ),
    );
  }

  _initStyle(int functionId) {
    switch (functionId) {
      case BRIGHTEN_SCREEN_TIME:
        _title = "亮屏时间设置";
        _mainTitle = "亮屏时间";
        _subTitle = "设置手表屏幕亮屏时间";
        _groupVisibility = false;
        break;
      case LANGUAGE:
        _title = "语言设置";
        _mainTitle = "语言设置";
        _subTitle = "设置手表显示的语言";
        _groupVisibility = false;
        break;

      case HOUR_TYPE:
        _title = "12/24小时制";
        _mainTitle = "12/24小时制";
        _subTitle = "设置手表以 “12小时制” 或 “24小时制” 显示时间";
        _rb0 = "24小时制";
        _rb1 = "12小时制";
        break;

      case ANTI_LOST:
        _title = "防丢设置";
        _mainTitle = "防丢设置";
        _subTitle = "开启防丢设置，.........";
        _rb0 = "关闭";
        _rb1 = "打开";
        break;

      case INCH_TYPE:
        _title = "公英制设置";
        _mainTitle = "公英制设置";
        _subTitle = "设置手表以 “公制” 或 “英制” 显示长度单位";
        _rb0 = "公制";
        _rb1 = "英制";
        break;

      case TEMPERATURE_TYPE:
        _title = "温度单位";
        _mainTitle = "温度单位";
        _subTitle = "设置手表以 “摄氏度” 或 “华氏度” 显示温度单位";
        _rb0 = "摄氏度";
        _rb1 = "华氏度";
        break;

      case SHAKE:
        _secondVisibility = true;
        _rb2Visibility = true;
        _title = "震动强度";
        _mainTitle = "震动强度";
        _subTitle = "设置手表震动强度";
        _rb0 = "弱";
        _rb1 = "中";
        _rb2 = "强";
        _mainTitle2 = "震动次数";
        _subTitle2 = "设置手表震动次数";
        break;
    }
  }

  ///获取Content信息内容
  String _getTrailingContent(ReceiveDataBean receiveDataBean) {
    print("function id :${receiveDataBean.functionId}");
    switch (receiveDataBean.functionId) {
      //亮屏时间
      case BRIGHTEN_SCREEN_TIME:
        int index = receiveDataBean.dataLongMap["brightScreenTime"] ?? 0;
        Log.d('index : $index');
        _content1 = _brightnessList[index];
        break;
      case LANGUAGE:
        int index = receiveDataBean.dataLongMap["language"] ?? 0;
        Log.d('index : $index');
        _content1 = _languageList[index];
        break;
    }
    return _content1;
  }

  ///获取Content信息内容
  String _getTrailingContent2(ReceiveDataBean receiveDataBean) {
    switch (receiveDataBean.functionId) {
      case SHAKE:
        int times = (receiveDataBean.dataLongMap['times']) ?? 0;
        _content2 = _shakeList[times];
        _contentIndex2 = times;
        Log.d(" times : $times ");
    }
    return _content2;
  }

  ///点击第一行content内容
  _clickFirstContent() async {
    var temp = _controller.receiveDataBean.value;
    switch (_functionId) {
      case BRIGHTEN_SCREEN_TIME:
        _contentIndex1 =
            await _showSheet(_brightnessList, 0) ?? (temp.dataLongMap["brightScreenTime"]!);
        _updateControllerBean();
        break;
      case LANGUAGE:
        _contentIndex1 = await _showSheet(_languageList, 0) ?? (temp.dataLongMap["language"]!);
        _updateControllerBean();
        break;
    }
  }

  ///点击第二行content内容
  _clickSecondContent() async {
    var temp = _controller.receiveDataBean.value;
    switch (_functionId) {
      case SHAKE:
        _contentIndex2 = await _showSheet(_shakeList, 0) ?? (temp.dataLongMap["times"]!);
        _updateControllerBean();
        break;
    }
  }

  ///用来临时更新controller中的bean。
  ///因为否则无法更新content中的内容。
  _updateControllerBean() {
    switch (_controller.receiveDataBean.value.functionId) {
      case BRIGHTEN_SCREEN_TIME:
        var temp = _controller.receiveDataBean.value;
        temp.dataLongMap["brightScreenTime"] = _contentIndex1;
        _controller.updateDataBean(temp);
        break;
      case SHAKE:
        var temp = _controller.receiveDataBean.value;
        temp.dataLongMap["times"] = _contentIndex2;
        _controller.updateDataBean(temp);
        break;
      case LANGUAGE:
        var temp = _controller.receiveDataBean.value;
        temp.dataLongMap["language"] = _contentIndex1;
        _controller.updateDataBean(temp);
        break;
    }
  }

  // 弹出底部菜单列表模态对话框
  Future<int?> _showSheet(List<String> list, int currIndex) {
    return showModalBottomSheet<int>(
      context: context,
      builder: (BuildContext context) {
        return ListView.builder(
          itemCount: list.length,
          itemBuilder: (BuildContext context, int index) {
            // 判断当前索引是否等于 currIndex
            // if (index == currIndex) {
            //   // 如果是，将列表项滚动到可视区域内
            //   WidgetsBinding.instance.addPostFrameCallback((_) {
            //     Scrollable.ensureVisible(
            //       context,
            //       alignment: 0.5, // 0.5 表示将列表项滚动到可视区域的中间位置
            //       duration: Duration(milliseconds: 300), // 滚动动画的持续时间
            //     );
            //   });
            // }
            return ListTile(
              title: Text(list[index]),
              onTap: () => Navigator.of(context).pop(index),
            );
          },
        );
      },
    );
  }

  /// 提交信息到手表
  _confirm() {
    //将数据传送给手表 write
    _controller.updateNeedClosePage(1);
    var mData = _makeDataForWatch();
    Log.d("发出去的数据:$mData");
    BleUtil.writeBleData(_mac, BleUtil.makeWriteData(functionId: _functionId, data: mData));
  }

  ///整合要提交的数据
  List<int> _makeDataForWatch() {
    List<int> result;
    switch (_functionId) {
      //"12/24小时制"
      case HOUR_TYPE:
      //"防丢设置"
      case ANTI_LOST:
      //"公英制设置"
      case INCH_TYPE:
      //"温度单位设置"
      case TEMPERATURE_TYPE:
        result = [_controller.radioIndex.value];
        break;
      case BRIGHTEN_SCREEN_TIME:
        result = ProtocolDataUtil.screenBright(_contentIndex1);
        break;
      case LANGUAGE:
        result = ProtocolDataUtil.language(_contentIndex1);
        break;
      case SHAKE:
        result = ProtocolDataUtil.shake(_controller.radioIndex.value + 1, _contentIndex2);
        Log.d("radio index: ${_controller.radioIndex.value + 1}  >>  $_contentIndex2");
        break;
      default:
        result = [0];
    }
    return result;
  }
}
